

package com.bolt.support.desensitization.resolver;


import com.bolt.common.reflect.ClassUtil;
import com.bolt.common.reflect.ReflectionUtil;
import com.bolt.support.desensitization.annotation.CascadeSensitive;
import com.bolt.support.desensitization.annotation.IgnoreSensitive;
import com.bolt.support.desensitization.support.InstanceCreators;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Modifier;

/**
 * 级联对象解析器
 */
public class CascadeTypeResolver implements TypeResolver<Object, AnnotatedType> {

    @Override
    public Object resolve(Object value, AnnotatedType annotatedType) {
        Class<?> clazz = value.getClass();
        Object newObject = InstanceCreators.getInstanceCreator(clazz).create();
        ClassUtil.getAllFields(clazz).parallelStream().forEach(field -> {
            Object fieldValue;
            AnnotatedType annotation = field.getAnnotatedType();
            if (!Modifier.isFinal(field.getModifiers()) && !annotation.isAnnotationPresent(IgnoreSensitive.class) && (fieldValue = ReflectionUtil.getFieldValue(value, field)) != null) {
                ReflectionUtil.setFieldValue(newObject, field, TypeResolvers.resolve(fieldValue, annotation));
            }
        });
        return newObject;
    }

    @Override
    public boolean support(Object value, AnnotatedType annotatedType) {
        return value != null && annotatedType.getDeclaredAnnotation(CascadeSensitive.class) != null;
    }

    @Override
    public int order() {
        return LOWEST_PRIORITY;
    }
}
